package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * 入住信息Service业务层处理
 *
 * @author alexis
 * @date 2025-05-22
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Resource
    private ElderMapper elderMapper;
    @Resource
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住信息
     *
     * @param id 入住信息主键
     * @return 入住信息
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住信息列表
     *
     * @param checkIn 入住信息
     * @return 入住信息
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住信息
     *
     * @param ids 需要删除的入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息信息
     *
     * @param id 入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //判断老人是否入住
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();
        wrapper.eq(idCardNo != null, Elder::getIdCardNo, idCardNo);
        Elder queryElder = elderMapper.selectOne(wrapper);
        if (!ObjectUtils.isEmpty(queryElder) && queryElder.getStatus() == 1) {
            throw new BaseException("该老人已入住");
        }
        //更新床位信息
        Bed bed = bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //新增或者更新老人数据
//        queryElder = insertOrUpdateElder(bed,queryElder, checkInApplyDto.getCheckInElderDto());
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(), elder);
        elder.setStatus(1);
        //床位相关信息
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        if (!ObjectUtils.isEmpty(queryElder) && queryElder.getStatus() != 1) {
            //老人数据存在，但禁用，更新老人数据
            elderMapper.updateById(elder);
        } else {
            //老人数据不存在，新增老人数据
            elderMapper.insert(elder);
        }

        //保存合同信息
        insertContract(elder, checkInApplyDto);

        //保存入住信息
        CheckIn checkIn = insertCheckIn(elder, checkInApplyDto);


        //保存入住配置信息
        insertCheckInConfig(checkIn.getId(),checkInApplyDto);


    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //入住信息及配置
        CheckIn checkIn = checkInMapper.selectById(id);
        LambdaQueryWrapper<CheckInConfig> configWrapper = new LambdaQueryWrapper<>();
        configWrapper.eq(CheckInConfig::getCheckInId,id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(configWrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkIn,checkInConfigVo);
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        //家属信息
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);

        //老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        BeanUtils.copyProperties(elder,checkInElderVo);
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        //签约办理
        LambdaQueryWrapper<Contract> contractWrapper =  new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId,elder.getId());
        Contract contract = contractMapper.selectOne(contractWrapper);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }

    //保存入住配置信息
    private void insertCheckInConfig(Long id, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(id);
        checkInConfigMapper.insert(checkInConfig);

    }

    //保存入住信息
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        //老人信息
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        //床位
        checkIn.setBedNumber(elder.getBedNumber());
        //开始、结束时间
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());

        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);

        checkInMapper.insert(checkIn);

        return checkIn;
    }

    //保存合同信息
    private void insertContract(Elder elder, CheckInApplyDto checkInApplyDto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        //老人信息
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        //合同编号
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        //开始、结束时间
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        contract.setStartDate(startDate);
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        contract.setStatus(startDate.isAfter(LocalDateTime.now()) ? 0 : 1);

        //保存
        contractMapper.insert(contract);
    }

    private Elder insertOrUpdateElder(Bed bed, Elder elder, CheckInElderDto checkInElderDto) {
        return null;
    }
}
